package com.tr.gateway.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wangxihao
 * @description: 非法字符过滤
 * @return {@link null}
 * @email wangxh0108@163.com
 **/
@Component
public class IllegalFilter implements GlobalFilter, Ordered {

    //获取配置文件的值
    @Value("${illegal_char}")
    private String illegalChar;

    //获取配置文件的值
    @Value("${illegal_ip}")
    private String illegalIp;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //得到请求ip
        String host = String.valueOf(request.getHeaders().getHost());
        System.out.println(host);
        int i = host.indexOf(":");
        String ip = host.substring(0, i);
        System.out.println(ip);
        String[] ips = illegalIp.split(",");
        HashMap hashMap = new HashMap();
        hashMap.put("code", 5000);
        for (String nip : ips) {
            if (ip.contains(nip)) {
                hashMap.put("msg", "非法IP");
                byte[] bytes = null;
                try {
                    bytes = JSON.toJSONString(hashMap).getBytes("GBK");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //spring的数据缓冲区
                DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(dataBuffer));
            }
            break;
        }

        //得到请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
//        URI uri = request.getURI();
//        System.out.println(uri);

//        System.out.println(queryParams.toString());
        //获取entry
        Set<Map.Entry<String, List<String>>> entries = queryParams.entrySet();
//        System.out.println(entries.toString());
        boolean status = false;
        for (Map.Entry<String, List<String>> entry : entries) {
            System.out.println(entry.getKey());  //每一个key
            System.out.println(entry.getValue()); //
            System.out.println(entry.getValue().get(0)); //每一个value

//            if(entry.getValue().get(0).toLowerCase().contains("tmd")){
//                status = true;
//                break;
//            }
            String[] illegalCharArray = illegalChar.split(",");
            for (String o : illegalCharArray) {
                if (entry.getValue().get(0).toLowerCase().contains(o)) {
                    status = true;
                    break;
                }
            }
        }

        if (status) {
            hashMap.put("msg", "非法字符");

            byte[] bytes = null;
            try {
                bytes = JSON.toJSONString(hashMap).getBytes("GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //spring的数据缓冲区
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

            return response.writeWith(Mono.just(dataBuffer));
        }

        //成功正确返回
        return chain.filter(exchange);
    }

    /**
     * 优先级 执行顺序  数字越小 优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 5;
    }

}
